package com.example.gokchinesefoodmappcdev.handler;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.gokchinesefoodmappcdev.dao.SysMenuDao;
import com.example.gokchinesefoodmappcdev.dao.SysOrgDao;
import com.example.gokchinesefoodmappcdev.dao.SysRoleDao;
import com.example.gokchinesefoodmappcdev.dao.SysUserDao;
import com.example.gokchinesefoodmappcdev.entity.SysOrg;
import com.example.gokchinesefoodmappcdev.entity.SysRole;
import com.example.gokchinesefoodmappcdev.entity.SysUser;
import com.example.gokchinesefoodmappcdev.util.JWTUtil;
import com.example.gokchinesefoodmappcdev.util.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*
* 登录成功后的显示，并产生JWT Token  返回给前端
* */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    SysUserDao userDao;
    
    @Autowired
    SysMenuDao menuDao;

    @Autowired
    SysRoleDao roleDao;
    @Autowired
    SysOrgDao orgDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        //1.登录成功后，取出用户的信息
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        String username = userDetails.getUsername();
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        String[] roles=new String[authorities.size()];
        int i=0;
        for (GrantedAuthority authority : authorities) {
            roles[i]=authority.getAuthority();
            i++;
        }

        Map<String,Object> payLoad=new HashMap<>();
        payLoad.put("username",username);
        payLoad.put("roles",roles);

        //2.生成jwt token
        String token = jwtUtil.createToken(payLoad);

        //根据用户名查出user信息
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        //先根据用户名查出对应的用户对象
        SysUser user1 = userDao.selectOne(wrapper);

        Integer userId = Math.toIntExact(user1.getUserId());
        List<Integer> menuList = menuDao.findMenuIdByUserId(userId);
        List<SysRole> role = roleDao.findRoleIdAndRoleNameByUserId(userId);
        List<SysOrg> org = orgDao.findOrgNameByUserId(userId);


        Map<String,Object> user=new HashMap<>();

        user.put("userId",user1.getUserId());
        user.put("orgId",user1.getOrgId());
        user.put("orgName",org.get(0).getName());
        user.put("username",user1.getUsername());
        user.put("password",user1.getPassword());
        user.put("email",user1.getEmail());
        user.put("mobile",user1.getMobile());
        user.put("status",user1.getStatus());
        user.put("userIdCreate",user1.getUserIdCreate());
        user.put("remark",user1.getRemark());
        user.put("gmtCreate",user1.getGmtCreate());
        user.put("gmtModified",user1.getGmtModified());
        user.put("nickName",user1.getNickName());
        user.put("job",user1.getJob());
        user.put("userType",user1.getUserType());
        user.put("merchantId",user1.getMerchantId());
        user.put("roleName",role.get(0).getRoleName());
        user.put("roleIdList",role.get(0).getRoleId());
        user.put("menuList",menuList);


        //3.响应给前端
        response.setContentType("application/json;charset=utf8");
        ResultData resultData = new ResultData(200, "验证成功",token,user);

        response.getWriter().write(JSONUtil.toJsonStr(resultData));
    }
}
